package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.POJO.Post;
import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.service.PostService;
import com.zhao.fishingguideserver.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    private PostService postService;

    /**
     * 发布帖子
     */
    @PostMapping("/create")
    public Result<String> createPost(@RequestBody Post post) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        post.setUserId(userId);
        
        String message = postService.createPost(post);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }

    /**
     * 更新帖子
     */
    @PutMapping("/update")
    public Result<String> updatePost(@RequestBody Post post) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        // 验证帖子是否属于当前用户
        Post existingPost = postService.getPostById(post.getId());
        if (existingPost == null) {
            return Result.error("帖子不存在");
        }
        if (!existingPost.getUserId().equals(userId)) {
            return Result.error("无权限修改此帖子");
        }
        
        String message = postService.updatePost(post);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/delete/{postId}")
    public Result<String> deletePost(@PathVariable Integer postId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        String message = postService.deletePost(postId, userId);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }

    /**
     * 获取帖子详情
     */
    @GetMapping("/detail/{postId}")
    public Result<Post> getPostDetail(@PathVariable Integer postId) {
        Post post = postService.getPostById(postId);
        if (post == null) {
            return Result.error("帖子不存在");
        }
        return Result.success(post);
    }

    /**
     * 获取帖子列表（分页）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getPosts(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        List<Post> posts = postService.getPosts(page, size);
        int total = postService.getPostCount();
        
        Map<String, Object> data = new HashMap<>();
        data.put("posts", posts);
        data.put("total", total);
        data.put("page", page);
        data.put("size", size);
        data.put("totalPages", (total + size - 1) / size);
        
        return Result.success(data);
    }

    /**
     * 根据分类获取帖子列表
     */
    @GetMapping("/category/{category}")
    public Result<Map<String, Object>> getPostsByCategory(
            @PathVariable String category,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        List<Post> posts = postService.getPostsByCategory(category, page, size);
        int total = postService.getPostCountByCategory(category);
        
        Map<String, Object> data = new HashMap<>();
        data.put("posts", posts);
        data.put("total", total);
        data.put("page", page);
        data.put("size", size);
        data.put("totalPages", (total + size - 1) / size);
        data.put("category", category);
        
        return Result.success(data);
    }

    /**
     * 根据用户ID获取帖子列表
     */
    @GetMapping("/user/{userId}")
    public Result<Map<String, Object>> getPostsByUserId(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        List<Post> posts = postService.getPostsByUserId(userId, page, size);
        int total = postService.getPostCountByUserId(userId);
        
        Map<String, Object> data = new HashMap<>();
        data.put("posts", posts);
        data.put("total", total);
        data.put("page", page);
        data.put("size", size);
        data.put("totalPages", (total + size - 1) / size);
        data.put("userId", userId);
        
        return Result.success(data);
    }

    /**
     * 搜索帖子
     */
    @GetMapping("/search")
    public Result<Map<String, Object>> searchPosts(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        List<Post> posts = postService.searchPosts(keyword, page, size);
        
        Map<String, Object> data = new HashMap<>();
        data.put("posts", posts);
        data.put("keyword", keyword);
        data.put("page", page);
        data.put("size", size);
        
        return Result.success(data);
    }

    /**
     * 获取热门帖子
     */
    @GetMapping("/hot")
    public Result<List<Post>> getHotPosts(@RequestParam(defaultValue = "10") Integer limit) {
        List<Post> posts = postService.getHotPosts(limit);
        return Result.success(posts);
    }

    /**
     * 点赞/取消点赞帖子
     */
    @PostMapping("/like/{postId}")
    public Result<String> toggleLike(@PathVariable Integer postId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Integer userId = Integer.parseInt(claims.get("id").toString());
        
        String message = postService.toggleLike(postId, userId);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }

    /**
     * 增加浏览次数
     */
    @PostMapping("/view/{postId}")
    public Result<String> incrementViewCount(@PathVariable Integer postId) {
        String message = postService.incrementViewCount(postId);
        return message.contains("成功") ? Result.success(message) : Result.error(message);
    }
}
